#include "onlinemusicwidget.h"
#include "ui_onlinemusicwidget.h"
#include <QPainter>
#include <QVBoxLayout>
#include <QScrollArea>
#include "aboutdialog.h"
#include <QPlainTextEdit>

//设定编码格式
#pragma execution_character_set("utf-8")

onlineMusicWidget::onlineMusicWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::onlineMusicWidget)
{
    ui->setupUi(this);
    // 去掉窗口标题栏
        this->setWindowFlag(Qt::FramelessWindowHint);

        // 禁止窗口改变尺寸大小
        this->setFixedSize(this->width(),this->height());

        // 播放进度条控件美化
        ui->horizontalSlider->setStyleSheet(
                    "QSlider::groove:horizontal {"
                    "border:1px solid skyblue;"
                    "background-color:skyblue;"
                    "height:10px;"
                    "border-radius:5px;"
                    "}"

                    "QSlider::handle:horizontal {"
                    "background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.7 white,stop:0.8 rgb(140,212,255));"
                    "width:20px;"
                    "border-radius:10px;"
                    "margin-top:-5px;"
                    "margin-bottom:-5px;}"

                    "horizontalSlider::sub-page:horizontal{"
                    "background:red;"
                    "margin:5px;"
                    "border-radius:5px;}"
                    );

        ui->horizontalSlider_Song->setStyleSheet(
                    "QSlider::groove:horizontal {"
                    "border:1px solid skyblue;"
                    "background-color:skyblue;"
                    "height:10px;"
                    "border-radius:5px;"
                    "}"

                    "QSlider::handle:horizontal {"
                    "background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.7 white,stop:0.8 rgb(140,212,255));"
                    "width:20px;"
                    "border-radius:10px;"
                    "margin-top:-5px;"
                    "margin-bottom:-5px;}"

                    "horizontalSlider::sub-page:horizontal{"
                    "background:red;"
                    "margin:5px;"
                    "border-radius:5px;}"
                    );
        //光标定位
        ui->lineEdit_inputMusic->setFocus();
        //初始化NetworkAccessManagers实例
        NetworkAccessManagers = new QNetworkAccessManager(this);

        iPos = 0; //初始化，播放状态为暂停播放

        //初始化文件对象
        docTextObject = ui->plainTextEdit_SongList->document();

        //设置为只读，我在ui界面已经设置过了，也可以使用代码设置
        ui->plainTextEdit_SongList->setReadOnly(true);

        //播放器对象实例化
        PlayerObjects = new QMediaPlayer(this);
        //实例化播放列表
        P_playerList = new QMediaPlaylist(this);

        //设置播放列表
        PlayerObjects->setMedia(P_playerList);
        //设置播放模式
        P_playerList->setPlaybackMode(QMediaPlaylist::Loop);

        //信号与槽处理
        connect(NetworkAccessManagers,SIGNAL(finished(QNetworkReply*)),this,SLOT(HandleDataBackFunc(QNetworkReply *)));
        connect(PlayerObjects,SIGNAL(positionChanged(qint64)),this,SLOT(HandleLCDNumberTimeChangeFunc(qint64)));
        connect(PlayerObjects,SIGNAL(durationChanged(qint64)),this,SLOT(HandleProgressTimeChangeFunc(qint64)));
        connect(PlayerObjects,SIGNAL(positionChanged(qint64)),this,SLOT(HandlePositionChangeFunc(qint64)));


        //处理标题显示歌曲信息动画字幕
        ui->label_DisplaySongTitle->setFont(QFont("宋体",14,QFont::Normal));
        strTitles = ui->label_DisplaySongTitle->text();
        //使用计时器
        QTimer *p_MoveTitle = new QTimer(this);
        iTitleChar = 0;
        //信号连接
        connect(p_MoveTitle,SIGNAL(timeout()),this,SLOT(titleMoveCaptionChar()));
        p_MoveTitle->start(1000); //时间暂时设为1秒

}

onlineMusicWidget::~onlineMusicWidget()
{
    delete ui;
}

//窗口背景绘制函数
void onlineMusicWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    //更改背景图片
    painter.drawPixmap(0,0,width(),height(),QPixmap(":/new/prefix1/images/background.jpg"));
}
// 功能：使用鼠标拖动窗口移动MP3播放器到桌面的任意位置
void onlineMusicWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_MouseDrag = true; //鼠标点击
        mouseStartPoint = event->globalPos(); //获取全局坐标（鼠标）
        widgetStartPoint = this->frameGeometry().topLeft(); //获取窗口坐标
    }
}

void onlineMusicWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(m_MouseDrag)
    {
        //获取鼠标移动距离
        QPoint m_Distance = event->globalPos()-mouseStartPoint;  //鼠标移动距离
        this->move(widgetStartPoint + m_Distance); //移动窗口
    }

}

void onlineMusicWidget::mouseReleaseEvent(QMouseEvent *event)
{
    //释放鼠标事件
    if(event->button() == Qt::LeftButton)
    {
        m_MouseDrag = false;
    }
}

//处理数据信息返回
void onlineMusicWidget::HandleDataBackFunc(QNetworkReply *pReply)
{
    //读取网络回馈数据
    QByteArySearchInfo = pReply->readAll();

    QJsonParseError JSonPError; //定义错误对象
    //将JSON格式文本转化为json文件对象
    QJsonDocument JSonDoc_RecvData = QJsonDocument::fromJson(QByteArySearchInfo,&JSonPError);
    if(JSonPError.error != QJsonParseError::NoError) //判断规则
    {
        QMessageBox::critical(this,"Prompt","提示：搜索歌曲获取json格式错误，请重新检查！",QMessageBox::Yes);
        return;
    }
    //QJsonObject使用函数object
    QJsonObject TotalJsonObject = JSonDoc_RecvData.object();
    //列出json里面所有的key
    QStringList strKeys = TotalJsonObject.keys();
    if(strKeys.contains("result")) //有数据信息
    {
        QJsonObject resultobject = TotalJsonObject["result"].toObject();

        //存储所有的keys
        QStringList strResultKeys = resultobject.keys();

        //是否搜索到歌曲
        if(strResultKeys.contains("songs"))
        {
            //测试
            //QMessageBox::information(this,"Prompt","请求到了歌曲",QMessageBox::Yes);
            QJsonArray array = resultobject["songs"].toArray();
            //for循环，查找歌曲信息
            for(auto isong:array)
            {
                QJsonObject jsonobject1 = isong.toObject();
                //获取歌曲ID
                I_MusicID = jsonobject1["id"].toInt();
                StrMusicName = jsonobject1["name"].toString();

                QStringList strkeys = jsonobject1.keys();
                if(strkeys.contains("artists"))
                {
                    QJsonArray artistsjsonarray = jsonobject1["artists"].toArray();
                    for(auto js:artistsjsonarray)
                    {
                        QJsonObject jsonobject2 = js.toObject();
                        StrSingerName = jsonobject2["name"].toString();

                    }
                }
            }
        }
    }
    QString strURL;
    strURL = QString("https://music.163.com/song/media/outer/url?id=%0").arg(I_MusicID);
    P_playerList->addMedia(QUrl(strURL));
    //显示歌曲名和歌手信息
    ui->plainTextEdit_SongList->appendPlainText("歌曲名："+StrMusicName);
    ui->plainTextEdit_Songer->appendPlainText("歌手："+StrSingerName);
}

//处理LCDNumber控件时间变化
void onlineMusicWidget::HandleLCDNumberTimeChangeFunc(qint64 duration)
{
    int int_Second = duration / 1000;//将毫秒转为秒
    int int_Minute = int_Second / 60; //得到分钟数
    int_Second = int_Second % 60; //余下的秒数

    QString strSongTime = QString::asprintf("%d:%d",int_Minute,int_Second);
    ui->lcdNumber_time->display(strSongTime);
}
//处理进度条控件变化
void onlineMusicWidget::HandleProgressTimeChangeFunc(qint64 duration)
{
    //设置进度条最大值
    ui->horizontalSlider->setMaximum(duration);

    int int_Value = P_playerList->currentIndex();

    QTextBlock qtextblocks = docTextObject->findBlockByNumber(int_Value);
    QString strTitle = qtextblocks.text();
    ui->label_DisplaySongTitle->setText(strTitle);

}

//处理播放位置变化
void onlineMusicWidget::HandlePositionChangeFunc(qint64 position)
{
    if(ui->horizontalSlider->isSliderDown())
    {
        return;
    }
    //设置滑块位置
    ui->horizontalSlider->setSliderPosition(position);
}

void onlineMusicWidget::HandlePlaySongFunc()
{

}

//处理动态字幕
void onlineMusicWidget::titleMoveCaptionChar()
{
    strTitles = ui->label_DisplaySongTitle->text();
    if(iTitleChar < strTitles.length())
    {
        QString strTemp = strTitles.mid(iTitleChar) + strTitles.mid(0,iTitleChar);
        ui->label_DisplaySongTitle->setText(strTemp);
        iTitleChar++;
    }
    else {
        iTitleChar = 0; //从头开始
    }
}


void onlineMusicWidget::on_plainTextEdit_3_textChanged()
{
    QPlainTextEdit *plainTextEdit = new QPlainTextEdit(this);
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setWidget(plainTextEdit);
    scrollArea->setWidgetResizable(true); // 允许调整文本编辑器的大小以适应滚动区域
    // 设置滚动条策略（但这不会强制显示滚动条）
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); // 总是显示水平滚动条（如果内容需要）
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); // 总是显示垂直滚动条（如果内容需要）
    // 将 scrollArea 添加到布局中

}
//关闭窗口
void onlineMusicWidget::on_pushButton_Exit_clicked()
{
    this->close();
}

void onlineMusicWidget::on_pushButton_Dectory_clicked()
{
    //文本设置相关参数
    //已经在ui界面设置完成
    /*
    QPushButton *button = new QPushButton(this);

    button->setStyleSheet("QPushButton { border: none; background-color: #FFFFFF;  }");

    button->setIcon(QIcon(":/path/to/your/image.png"));

    button->setText("");
    */
    QString strCurrentPaths = QDir::homePath();
    QString strDlgTitle = "请选择MP3音乐文件";
    QString strFilters = "所有文件(*.*);;音频文件(*.mp3);;mp3文件(*.mp3)";
    QStringList strMp3FileList = QFileDialog::getOpenFileNames(this,strDlgTitle,strCurrentPaths,strFilters);

    if(strMp3FileList.count()<1)
    {
        return;
    }
    for(int i=0;i<strMp3FileList.count();i++)
    {
        QString strFiles = strMp3FileList.at(i);
        //添加文件到播放列表
        P_playerList->addMedia(QUrl::fromLocalFile(strFiles));
        QFileInfo qFileInfo(strFiles);
        //将歌曲添加到控件中
        ui->plainTextEdit_History_Song->appendPlainText(qFileInfo.fileName());
    }
    //添加完毕，立即播放
    if(PlayerObjects->state() != QMediaPlayer::PlayingState)
    {
        P_playerList->setCurrentIndex(0);  //从第一首开始播放
    }
    PlayerObjects->play();
}

void onlineMusicWidget::on_pushButton_About_clicked()
{
    AboutDialog * dialog = new AboutDialog(this);
    //更改窗口位置
    /*
    QRect qRect = geometry();
    int X_ = qRect.x()+120;  //值随便定
    int Y_ = qRect.y()+200;
    dialog->setGeometry(X_,Y_,0,0);  //后面的两个参数根据窗口大小调整

    */
   //自行选择
    dialog->exec(); //阻塞 ，不可以拖动窗口
    //dialog->show();  //可以拖动窗口
}

//查询歌曲
void onlineMusicWidget::on_pushButton_Search_clicked()
{
    QString str1,str2;
    str1 = ui->lineEdit_inputMusic->text();
    QMessageBox::information(this,"Prompt",str1,QMessageBox::Yes);
    str2="http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s={"+str1+"}&type=1&offset=0&total=true&limit=1";
    //定义一个请求对象
    QNetworkRequest networkRequest;

    //将请求格式设置给对应请求对象
    networkRequest.setUrl(str2);

    //使用QNetworkAccessManager类对应的API发送GET
    NetworkAccessManagers->get(networkRequest);//请求处理


}

//播放
void onlineMusicWidget::on_pushButton_PlaySong_clicked()
{
    //如果状态为0，则为停止状态，可以播放
    if(iPos == 0)
    {
        PlayerObjects->play();
        iPos = 1;
    }
    else if(P_playerList->currentIndex()<0)
    {
        P_playerList->setCurrentIndex(0);
    }
    PlayerObjects->play();

}
//播放暂停
void onlineMusicWidget::on_pushButton_PauseSong_clicked()
{
    if(iPos == 1)
    {
        PlayerObjects->pause();
        iPos = 0;
    }
}

//从头开始播放
void onlineMusicWidget::on_pushButton_Stop_PlaySong_clicked()
{
    PlayerObjects->stop();
}

//上一曲
void onlineMusicWidget::on_pushButton_PreviousSong_clicked()
{
    int m_index = P_playerList->currentIndex();//当前的序列号
    int m_indexSum = P_playerList->mediaCount(); //总的序列号
    if(m_index > 0) //如果已经播放过了
    {
        m_index = m_index - 1;
        P_playerList->setCurrentIndex(m_index); //跳转到序列号所在的位置
        PlayerObjects->play();//播放
    }
    else  //从头开始还未播放
    {
        m_index = m_indexSum - 1;
        P_playerList->setCurrentIndex(m_index);
        PlayerObjects->play();
    }
}
//下一曲
void onlineMusicWidget::on_pushButton_NextSong_clicked()
{
    int m_index = P_playerList->currentIndex();//当前的序列号
    int m_indexSum = P_playerList->mediaCount(); //总的序列号
    if(m_index < m_indexSum)
    {
        m_index = m_index + 1;
        P_playerList->setCurrentIndex(m_index); //跳转到序列号所在的位置
        PlayerObjects->play();//播放
    }
    else  //从头开始播放
    {
        m_index = 0;
        P_playerList->setCurrentIndex(m_index);
        PlayerObjects->play();
    }

}

//静音状态，图标切换
void onlineMusicWidget::on_pushButton_closeSong_clicked()
{
    bool bMutexState = PlayerObjects->isMuted();
    PlayerObjects->setMuted(!bMutexState);
    if(bMutexState)
    {
        ui->pushButton_closeSong->setIcon(QIcon(":/new/prefix1/images/OpenSong.jpg"));
    }
    else
    {
        ui->pushButton_closeSong->setIcon(QIcon(":/new/prefix1/images/CloseSong.jpeg"));
    }
}

//音量控制
void onlineMusicWidget::on_horizontalSlider_Song_valueChanged(int value)
{
    PlayerObjects->setVolume(value);
}

//播放进度控制条
void onlineMusicWidget::on_horizontalSlider_valueChanged(int value)
{
    PlayerObjects->setPosition(value);
}
